import { authApi } from '@/api/modules/auth'

/**
 * Token管理工具
 */
class TokenManager {
  private static instance: TokenManager
  private refreshTokenPromise: Promise<any> | null = null

  private constructor() {}

  static getInstance(): TokenManager {
    if (!TokenManager.instance) {
      TokenManager.instance = new TokenManager()
    }
    return TokenManager.instance
  }

  /**
   * 获取访问Token
   */
  getAccessToken(): string | null {
    return localStorage.getItem('access_token')
  }

  /**
   * 设置访问Token
   * @param token 访问Token
   */
  setAccessToken(token: string): void {
    localStorage.setItem('access_token', token)
  }

  /**
   * 移除访问Token
   */
  removeAccessToken(): void {
    localStorage.removeItem('access_token')
  }

  /**
   * 获取刷新Token
   */
  getRefreshToken(): string | null {
    return localStorage.getItem('refresh_token')
  }

  /**
   * 设置刷新Token
   * @param token 刷新Token
   */
  setRefreshToken(token: string): void {
    localStorage.setItem('refresh_token', token)
  }

  /**
   * 移除刷新Token
   */
  removeRefreshToken(): void {
    localStorage.removeItem('refresh_token')
  }

  /**
   * 刷新Token
   */
  async refreshToken(): Promise<string | null> {
    // 防止并发刷新
    if (this.refreshTokenPromise) {
      return this.refreshTokenPromise
    }

    const refreshToken = this.getRefreshToken()
    if (!refreshToken) {
      return null
    }

    this.refreshTokenPromise = authApi.refreshToken({ refreshToken })
      .then(response => {
        const { accessToken, refreshToken: newRefreshToken } = response.data
        this.setAccessToken(accessToken)
        this.setRefreshToken(newRefreshToken)
        return accessToken
      })
      .catch(() => {
        // 刷新失败，清除Token
        this.removeAccessToken()
        this.removeRefreshToken()
        return null
      })
      .finally(() => {
        this.refreshTokenPromise = null
      })

    return this.refreshTokenPromise
  }

  /**
   * 检查Token是否过期
   */
  isTokenExpired(): boolean {
    const token = this.getAccessToken()
    if (!token) return true

    try {
      const base64Url = token.split('.')[1]
      if (!base64Url) return true

      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
      const payload = JSON.parse(atob(base64))
      const exp = payload.exp
      if (!exp) return true

      // 提前5分钟刷新Token
      return Date.now() >= exp * 1000 - 5 * 60 * 1000
    } catch {
      return true
    }
  }
}

export default TokenManager.getInstance()
